# -*- -*- -*- -*- -*- -*- -*-
# @Author  : mengzhe
# @Time    : 2025/1/13 16:40
# @File    : plc.py
# @function: 工控机执行指令集  Programmable Logic Controller
# @input   :
# @output  :
# @Software: PyCharm 
# -*- -*- -*- -*- -*- -*- -*-
import  subprocess
import utils
import os

# 定义指令集合
commands = {
    "cpu_serial":           "cat /proc/cpuinfo | grep -i 'serial' | awk -F': ' '{print $2}'",
    "manufacture_date":     "date -d '2024-10-23' +'%Y%m%d'",
    "cpu_usage":            r"top -bn1 | grep 'Cpu(s)' | sed 's/.*, *\([0-9.]*\)%* id.*/\\1/' | awk '{print 100 - $1}'",
    "memory_usage":         "free | grep Mem | awk '{print $3/$2 * 100.0}'",
    "disk_usage":           "df / | grep / | awk '{ print $5 }' | tr -d '%'",
    "radar_status":         "ping -c 1 192.168.1.135 > /dev/null && echo '01' || echo '00'",
    "camera_status":        "ping -c 1 192.168.1.64 > /dev/null && echo '01' || echo '00'",
    "gnss_status":          "ls /dev/ttyUSB0 > /dev/null 2>&1 && echo '01' || echo '00'",
    "weather_status":       "ls /dev/ttyUSB1 > /dev/null 2>&1 && echo '01' || echo '00'",
    "router_status":        "ping -c 1 192.168.1.1 > /dev/null && echo '01' || echo '00'",
    "algorithm_version":    "printf '%02d %02d\n' 0 12",
    # 更多指令可以继续添加...
}

# 使用字典中的命令
def execute_command(command_name):
    command = commands.get(command_name)
    if command:
        result = subprocess.getoutput(command)
        return result
    else:
        return f"Command '{command_name}' not found."


class PLC:
    def __init__(self, sensor_id, name):
        self.sensor_id = sensor_id
        self.name = name
        self.status = "IDLE"

        self.device_serial      ="00 00 00 00 00 00 00 00"  # 设备编号
        self.manufacture_date   ="20 25 01 13"  # 生产日期
        self.cpu_usage          ="00 00 00 00"       # CPU使用率
        self.memory_usage       ="00 00 00 00"       # 内存使用率
        self.disk_usage         ="00 00 00 00"       # 磁盘使用率
        self.radar_status       ="00"       # 雷达连接状况
        self.camera_status      ="00"       # 摄像头状况
        self.gnss_status        ="00"       # GNSS状况
        self.weather_status     ="00"       # 气象站状况
        self.router_status      ="00"       # 路由器状况
        self.backup_1           ="00 00"        # 备用1
        self.backup_2           ="00 00"        # 备用2
        self.backup_3           ="00 00"        # 备用3
        self.plc_version        ="01 00"        # 工控机硬件版本
        self.algorithm_version  ="01 00"        # 算法版本

    def active_report(self):
        # 测试指令集合
        # 55 AA 1A 00 00 00 00 00 01 00 01 00 00 00 00 00 00 00 00 00 00 00
        # 主动上报，需要按照当前的编号更新指令累计
        # 实现Linux和windows的区别处理
        if os.name == 'posix':  # Linux/macOS
            print("执行 Linux 操作...")
            self.device_serial = utils.format_serial(execute_command(command_name="cpu_serial"))
            # 指定数据的直接保持原始值不进行修改
            self.cpu_usage = utils.float32_to_float32_hex(float(execute_command(command_name="cpu_usage")))
            self.memory_usage = utils.float32_to_float32_hex(float(execute_command(command_name="memory_usage")))
            self.disk_usage = utils.float32_to_float32_hex(float(execute_command(command_name="disk_usage")))

            self.radar_status = execute_command(command_name="radar_status")
            self.camera_status = execute_command(command_name="camera_status")
            self.gnss_status = execute_command(command_name="gnss_status")
            self.weather_status = execute_command(command_name="weather_status")
            self.router_status = execute_command(command_name="router_status")

            result = ' '.join(
                [self.device_serial, self.manufacture_date, self.cpu_usage, self.memory_usage, self.disk_usage,
                 self.radar_status, self.camera_status, self.gnss_status, self.weather_status, self.router_status,
                 self.backup_1, self.backup_2, self.backup_3, self.plc_version, self.algorithm_version])
            print(f"指令执行正常，有返回数据: {result}")

        else:  # Windows
            print("执行 Windows 操作...")

            result ='af 30 40 33 6a 45 bd 65 20 25 01 13 00 00 c8 42 d5 09 22 41 00 00 c8 42 01 01 01 00 01 00 00 00 00 00 00 01 00 01 00'
            print(f"自定义指令执行正常，有返回数据: {result}")


        result_byte = utils.str_bytes_2_bytes(result)
        # print(
        #     f"设备编号{execute_command(command_name='cpu_serial')} 生产日期 {self.manufacture_date} CPU{float(execute_command(command_name='cpu_usage'))} 内存 {float(execute_command(command_name='memory_usage'))} 磁盘 {float(execute_command(command_name='disk_usage'))}")
        print(
            f"雷达{self.radar_status} 摄像头{self.camera_status} GNSS {self.gnss_status} 气象站 {self.weather_status} 路由器 {self.router_status}")
        print(f"硬件版本{self.plc_version} 算法版本{self.algorithm_version}")

        return result_byte


    def query_report(self):
        # 55 AA 1A 00 00 00 00 00 01 00 01 00 00 00 00 00 00 00 00 00 00 00
        # 服务器查询指令，指令累计使用查询指令。
        # 实现Linux和windows的区别处理
        if os.name == 'posix':  # Linux/macOS
            print("执行 Linux 操作...")
            self.device_serial = utils.format_serial(execute_command(command_name="cpu_serial"))
            # 指定数据的直接保持原始值不进行修改
            self.cpu_usage = utils.float32_to_float32_hex(float(execute_command(command_name="cpu_usage")))
            self.memory_usage = utils.float32_to_float32_hex(float(execute_command(command_name="memory_usage")))
            self.disk_usage = utils.float32_to_float32_hex(float(execute_command(command_name="disk_usage")))

            self.radar_status = execute_command(command_name="radar_status")
            self.camera_status = execute_command(command_name="camera_status")
            self.gnss_status = execute_command(command_name="gnss_status")
            self.weather_status = execute_command(command_name="weather_status")
            self.router_status = execute_command(command_name="router_status")

            result = ' '.join(
                [self.device_serial, self.manufacture_date, self.cpu_usage, self.memory_usage, self.disk_usage,
                 self.radar_status, self.camera_status, self.gnss_status, self.weather_status, self.router_status,
                 self.backup_1, self.backup_2, self.backup_3, self.plc_version, self.algorithm_version])
            print(f"指令执行正常，有返回数据: {result}")

        else:  # Windows
            print("执行 Windows 操作...")

            result ='af 30 40 33 6a 45 bd 65 20 25 01 13 00 00 c8 42 d5 09 22 41 00 00 c8 42 01 01 01 00 01 00 00 00 00 00 00 01 00 01 00'
            print(f"自定义指令执行正常，有返回数据: {result}")


        result_byte = utils.str_bytes_2_bytes(result)
        # print(
        #     f"设备编号{execute_command(command_name='cpu_serial')} 生产日期 {self.manufacture_date} CPU{float(execute_command(command_name='cpu_usage'))} 内存 {float(execute_command(command_name='memory_usage'))} 磁盘 {float(execute_command(command_name='disk_usage'))}")
        print(
            f"雷达{self.radar_status} 摄像头{self.camera_status} GNSS {self.gnss_status} 气象站 {self.weather_status} 路由器 {self.router_status}")
        print(f"硬件版本{self.plc_version} 算法版本{self.algorithm_version}")

        return result_byte



    def read_data(self):
        # 模拟从传感器读取数据
        print(f"{self.name} is reading data...")
        result = ' '.join(
            [self.plc_version, self.algorithm_version])
        return result

    def test(self):
        # 模拟从传感器读取数据
        # print(f"{self.name} is reading data...")
        result='PLC data update'
        return result

    def configure(self):
        # 模拟传感器配置
        """生成从 '01' 到 'FF' 的字符串"""
        # 生成字符串
        result = bytes(range(1, 256))

        result  = result+result+result+result+result+result+result+result+result

        print(f"{self.name} is moni data...")
        return result


    def reset(self):
        # 模拟传感器复位
        self.status = "IDLE"
        return f"{self.name} reset to default state"


# if __name__ == '__main__':
#     plc = PLC(sensor_id="PLC001", name="Industrial_PLC")
#     plc.active_escalation()
